package com.unbank.bhi.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.unbank.bhi.dao.BhiJDBC;

public class BhiLogin {

	private static Log logger = LogFactory.getLog(BhiLogin.class);
	BhiAnalyze bhiAnalyze = new BhiAnalyze();

	public void console() {
		System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
		WebDriver driver = new ChromeDriver();
		driver.manage().window().maximize();
		login("unbank", "ylxsjb", driver);
		userConsole(driver);
		BhiJDBC.close();
		driver.quit();

	}

	private void userConsole(WebDriver driver) {
		// 登陆
		while (true) {
			String a = driver.getCurrentUrl();
			if (a.contains("http://www.bhi.com.cn/Login/login.aspx")) {
				try {
					Thread.sleep(30 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			} else {
				break;
			}

		}
		// 登陆成功
		driver.get("http://www.bhi.com.cn/projects/ItemList.aspx?a=1&p=t");
		// try {
		// Thread.sleep(5000);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }
		// 获取每页的项目的URL
		List<String> urls = new ArrayList<String>();
		int i = 0;
		while (i < 85) {

			String a = driver.getPageSource();
			if (a.contains("下一页")) {

				String temp = driver.getPageSource();
				// 获取每页的项目的URL
				urls.addAll(getDocument(temp));
				// 如果有下一页点击到下一页
				WebElement userElement = driver.findElement(By.linkText("下一页"));
				if (userElement != null) {
					userElement.click();
				} else {
					break;
				}
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				break;
			}
			i++;
		}

		// 得到URL 后,获取真正的项目数据
		getStr(urls, driver);

	}

	// 获取当前页面的项目的URL
	public List<String> getDocument(String html) {
		Document doc = Jsoup.parse(html);
		Elements tableElements = doc.select("table.listTable");
		Elements tdElements = tableElements.get(0).select("td[align=left]");
		List<String> urls = new ArrayList<String>();
		for (Element element : tdElements) {
			Elements aElements = element.select("a");
			urls.add("http://www.bhi.com.cn/projects/"
					+ aElements.get(0).attr("href"));
		}
		return urls;
	}

	// 解析真正的项目内容
	private void getStr(List<String> urls, WebDriver webDriver) {
		for (String string : urls) {
			logger.info(string);
			webDriver.get(string);

			waitForPageLoaded(webDriver);
			// try {
			// Thread.sleep(5000);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }
			try {
				bhiAnalyze.insertbhi(webDriver);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// documents.add(webDriver.getPageSource());
		}
	}

	// 登录
	public boolean login(String username, String password, WebDriver driver) {
		driver.get("http://www.bhi.com.cn/Login/login.aspx");
		// try {
		// Thread.sleep(5000);
		// } catch (InterruptedException e1) {
		// e1.printStackTrace();
		// }
		WebElement userElement = driver.findElement(By.id("username"));
		WebElement passwordElement = driver.findElement(By.id("loginPassword"));
		userElement.sendKeys(username);
		passwordElement.sendKeys(password);
		return true;
	}

	public void waitForPageLoaded(WebDriver driver) {
		ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
			public Boolean apply(WebDriver driver) {
				return ((JavascriptExecutor) driver).executeScript(
						"return document.readyState").equals("complete");
			}
		};
		Wait<WebDriver> wait = new WebDriverWait(driver, 5000);
		try {
			wait.until(expectation);
		} catch (Throwable error) {
			logger.info(error);
		}
	}

}
